package com.cd.university.common.lru;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author 陈栋
 * @create 2021/12/11 17:09
 */
public class LRULinkedHashMap<K,V> extends LinkedHashMap<K,V> implements LRUCacheFactory {
    private int capacity;

    public LRULinkedHashMap(int capacity) {
        super(capacity, 0.75F, true);
        this.capacity = capacity;
    }

    @Override
    public LRUCacheFactory createLRUCache(int capacity) {
        return new LRULinkedHashMap(capacity);
    }

    @Override
    public LRUCacheFactory modifyCapacity(int capacity) {
        LRULinkedHashMap newLruLinkedHashMap = new LRULinkedHashMap(capacity);
        for (Map.Entry<K, V> kvEntry : this.entrySet()) {
            newLruLinkedHashMap.put(kvEntry.getKey(),kvEntry.getValue());
        }
        return newLruLinkedHashMap;
    }

    @Override
    public Object put(Object key, Object value) {
        return super.put((K) key, (V) value);
    }

    @Override
    public int size() {
        return super.size();
    }

    /**
     * LRU算法
     * @param eldest
     * @return
     */
    @Override
    protected boolean removeEldestEntry(Map.Entry eldest) {
        return size() > capacity;
    }
}
